package org.digitalsoul.switchplugin.patterns;

import org.digitalsoul.switchplugin.SwitchFile;
import org.eclipse.core.runtime.IPath;

import java.io.File;
import java.util.List;


public class FileLocationPattern implements IPattern {

    private final String matchingLocation;
    private final PathMatcher matcher;

    public FileLocationPattern(String matchingLocation) {
        this.matchingLocation = matchingLocation;
        matcher = new PathMatcher();
    }
    
    public SwitchFile applyToFile(IPattern previousPattern, SwitchFile file) {
        IPath projectPath = file.getProject().getLocation();
        File searchFolder = new File(projectPath.toPortableString());
        PathBuilder builder = new PathBuilder();
        builder.build(searchFolder);
        List<String> paths = builder.getPaths();
        String matchedPath = null;
        for (String path : paths) {
          if (matcher.match(path, matchingLocation)) {
              matchedPath = path;
              break;
          }
        }
        file.changeLocation(matchedPath);
        return file;
    }

    public PatternType getType() {
        return PatternType.FILE_LOCATION;
    }

    public boolean matches(SwitchFile file) {
        return matcher.match(file.getLocation(), matchingLocation);
    }

    public SwitchFile undoFile(SwitchFile file) {
        return file;
    }

    public String getMatchingLocation() {
        return matchingLocation;
    }
    
    @Override
    public String toString() {
        return "file-loc: " + matchingLocation;
    }
}
